package com.xmfh.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmfh.wemedia.common.Result;
import com.xmfh.wemedia.exception.DatabaseInsertionError;
import com.xmfh.wemedia.exception.UserAlreadyExistsException;
import com.xmfh.wemedia.mapper.DdUserMapper;
import com.xmfh.wemedia.model.DdPermission;
import com.xmfh.wemedia.model.DdRole;
import com.xmfh.wemedia.model.DdUser;
import com.xmfh.wemedia.service.IDdUserService;
import com.xmfh.wemedia.vo.PreRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-04-03
 *
 *
 */
@Service
public class DdUserServiceImpl extends ServiceImpl<DdUserMapper, DdUser> implements IDdUserService,UserDetailsService {

    //用户表的持久层
    @Autowired(required = false)
    private DdUserMapper ddUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("进来了");
        // 1.根据用户名查询用户对象(手机号)
        DdUser user = ddUserMapper.findUserByUserName(username);
        // 2.判断是否能够查询到用户,没有该用户表示用户名不存在
        if (user == null) {
            return null;
        }
        // 3.根据用户id查询用户的所有权限
        List<DdPermission> permissions = ddUserMapper
                .findUserPermissionsById(user.getId());
        // 4.将权限的集合转换为String类型数组,并赋值
        String[] auth = new String[permissions.size()];
        int i = 0;
        for (DdPermission p : permissions) {
            auth[i] = p.getName();
            i++;
        }
        // 查询当前用户所有角色
        List<DdRole> roles = ddUserMapper.findUserRolesById(
                user.getId());
        // 数组扩容
        auth = Arrays.copyOf(auth,
                auth.length + roles.size());
        //  {"/getid","/add","/update","/upload",null}
        for (DdRole role : roles) {
            auth[i++] = role.getName();
        }
        // 5.构建UserDetails对象
        UserDetails details = org.springframework.security
                .core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auth)
//                //设置当前账户是否锁定 false表示不锁定
//                .accountLocked(user.get()==1)
//                //设置当前账户是否可用 false表示可用
//                .disabled(user.getEnabled()==0)
                .build();
        // 6.返回UserDetails对象
        log.debug("用户信息详情--:" + details);
        return details;
    }

    /**
     * 我的个人信息
     * @return
     */
    @Override
    public Result getMe() {
        //获取当前会话
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session=request.getSession();
        DdUser user=(DdUser) session.getAttribute("ddUser");
        if (user!=null){
            return Result.ok(user);
        }else{
            return Result.error("您还没有登录哦！");
        }
    }

    /**
     * 登出
     */
    @Override
    public void logout() {
        //获取当前会话
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        session.setAttribute("ddUser", null);
    }

    @Override
    public void insertNewUser(PreRegisterVo preRegisterVo) {
        if (ddUserMapper.findUserByUserName(preRegisterVo.getUsername()) != null)
            throw new UserAlreadyExistsException("用户名已存在");

        /*
        * #{username},
                #{password},
                #{nickname},
                #{fabulous},
                #{fans},
                #{follow}
        * */
        DdUser user = new DdUser()
                .setUsername(preRegisterVo.getUsername())
                .setPassword(preRegisterVo.getPassword())
                .setNickname(preRegisterVo.getNickname())
                .setFabulous(0)
                .setFans(0)
                .setFollow(0)
                .setDesc(preRegisterVo.getDesc());

        if (ddUserMapper.insertNewUser(user) != 1)
            throw new DatabaseInsertionError("数据库发生错误");
    }

}
